<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
		<link rel="stylesheet" href="./scripts/estilo.css" type="text/css"/>
		<title>Sistran Maps - 2010 Beta Test</title>
		<script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA9N7ZgI7iRfg1ef5wnMehwRRHIZ64MQDS_PgfLYruevxWF5hHaxSR5O8sCmzo1VF6Jo25Txzo3miAig"</script>
		<script type="text/javascript" src="http://www.google.com/uds/api?file=uds.js&amp;v=1.0"</script>
    <script type="text/javascript" src="./scripts/icons.js"</script>
    <script type="text/javascript">
    function initialize()
    {
      if (GBrowserIsCompatible())
      {
        //Define a largura da janela.
        var width  = (parseInt(document.documentElement.clientWidth) - 10);
        //Define a altura da janela.
        var height = (parseInt(document.documentElement.clientHeight) - 25);

        //Define a posicao inicial do mapa e o nivel de zoom.
        var latInicial = "-23.9697823";
        var lngInicial = "-46.3709677";          
		var zoom_level = 17;
        var pos_inicial = new GLatLng(latInicial, lngInicial);

        //Inicializa o geocodificador e o mapa.
        var geocoder = new GClientGeocoder();
        var map = new GMap2(document.getElementById("map_canvas"), {size: new GSize(width,height)});
        
        //Define o centro do mapa baseado em sua posicao inicial, e o nivel de zoom.
        map.setCenter(pos_inicial,zoom_level);
        
        //Define o tipo do mapa a ser exibido (G_NORMAL_MAP / G_SATELLITE_MAP / G_HYBRID_MAP)
        map.setMapType(G_NORMAL_MAP);
        
        //Adiciona controle que permite alternar entre os tipos de mapa.
        map.addControl(new GHierarchicalMapTypeControl());
        
        //Adiciona controle de botoes do mapa
        map.addControl(new GLargeMapControl());
        
        //Adiciona controle com a exibicao de escala do mapa.
        //map.addControl(new GScaleControl());
        
        //Recupera informacoes do banco de dados atraves de XML.
        GDownloadUrl("scripts/xml.php", function(data) 
        {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) 
          {
            var point   = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
            var name    = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
            var type    = markers[i].getAttribute("type");
            var marker  = createMarker(point, name, address, type);
            map.addOverlay(marker);
          }
        });
        
        function createMarker(point, name, address, type, compl) 
        {
          var marker = new GMarker(point, customIcons[name]);
          var html = "<b>Tipo: </b>" + name + "<br/><b>Logradouro: </b>" + address + "<br/><b>Posição: </b>" + type;
          GEvent.addListener(marker, 'click', function() 
          {
            marker.openInfoWindowHtml(html);
          });
          return marker;
        }

        //Adiciona um Listener para o clique no mapa, disparando a funcao getAddress.
        GEvent.addListener(map, "click", getAddress);

        function getAddress(overlay, pos_inicial) 
        {
          if (pos_inicial != null) 
          {
            geocoder.getLocations(pos_inicial, showAddress);
          }
        }

        function showAddress(response) 
        {
          if (!response || response.Status.code != 200) 
          {
            alert("Erro!" + '<br/>' + "Status Code:" + response.Status.code);
          } 
          else 
          {
            place = response.Placemark[0];
            var latClique = place.Point.coordinates[1];
            var lngClique = place.Point.coordinates[0];              
            point = new GLatLng(latClique, lngClique);
            marker = new GMarker(point);
            map.addOverlay(marker);
            marker.openInfoWindowHtml
            (
              '<b>Posição Desejada:</b>' + response.name + '<br/>' + 
              '<b>Posição Aproximada:</b>' + latClique + "," + lngClique + '<br/>' + 
              '<b>Endereço:</b> ' + place.address + '.<br/>' + 
              '<hr>' 
            );
          }
        }
		
		var encodedPolyline = new GPolyline.fromEncoded(
					{
						color: "navy",
						weight: 10,
						//points: "r_iqChn_zGoJlT~DnDuHzGcChMC|Psi@hsAeFrcA}z@jo@",
						//levels: "BBBBBBBBB",
						points: "n|gqC`bbzG~B{EvEeL`DdCiEvKqJgF",
						levels: "BBBBBB",
						zoomFactor: 32,
						numLevels: 4
					}
					);
					map.addOverlay(encodedPolyline);								
      }
    }

    function exibeEndereco(address)
    {
      alert(address);
    }

    GSearch.setOnLoadCallback(initialize);
    </script>
  </head>
	<body onload="initialize()" onunload="GUnload()">
    <form name="formMaps"> 
      <p>
        <?php
          define("MAPS_HOST", "maps.google.com.br");
          define("KEY", "ABQIAAAA9N7ZgI7iRfg1ef5wnMehwRRHIZ64MQDS_PgfLYruevxWF5hHaxSR5O8sCmzo1VF6Jo25Txzo3miAig");

          // Opens a connection to a MySQL server
          $connection = mysql_connect("localhost", "root", "");		
          if (!$connection)	
          {
            die("Not connected : " . mysql_error());
          }

          // Set the active MySQL database
          $db_selected = mysql_select_db("maps1", $connection);
          if (!$db_selected) 
          {
            die("Can\'t use db : " . mysql_error());
          }

          // Select all the rows in the markers table
          $query = "select * from markers order by id asc";				
          $result = mysql_query($query);				
          if (!$result) 
          {
            die("Invalid query: " . mysql_error());
          }

          // Initialize delay in geocode speed
          $delay = 0;
          $base_url = "http://" . MAPS_HOST . "/maps/geo?output=csv&key=" . KEY;

          // Iterate through the rows, geocoding each address				
          while ($row = @mysql_fetch_assoc($result)) 
          {
            $geocode_pending = true;
            while ($geocode_pending) 
            {
              $id = $row["id"];
              $name = $row["name"];
              $address = $row["address"];
              $request_url = $base_url . "&q=" . urlencode($address);
              $csv = file_get_contents($request_url) or die("url not loading");
              $csvSplit = explode(",", $csv);
              $status = $csvSplit[0];
              $lat = $csvSplit[2];
              $lng = $csvSplit[3];
              if (strcmp($status, "200") == 0) 
              {
                // successful geocode
                $geocode_pending = false;
                $lat = $csvSplit[2];
                $lng = $csvSplit[3];
                $query = sprintf("UPDATE markers " .
                       " SET lat = '%s', lng = '%s' " .
                       " WHERE id = %s LIMIT 1;",
                       mysql_real_escape_string($lat),
                       mysql_real_escape_string($lng),
                       mysql_real_escape_string($id));
                $update_result = mysql_query($query);
                
                /*
                echo $id . ".) " . strtoupper($name) . ": " . $address . "<br>";
                echo "Coordernadas... Lat: " . $lat . " / "  . "Long: " . $lng . "<hr>";
                echo "Received status: " . $status . "<hr>";
                */
                
                if (!$update_result) 
                {
                  die("Invalid query: " . mysql_error());
                }
              } 
              else if (strcmp($status, "620") == 0) 
              {
                // sent geocodes too fast
                $delay += 100000;
              } 
              else 
              {
                // failure to geocode
                $geocode_pending = false;
                echo "Address " . $address . " failed to geocoded. ";
                echo "Received status " . $status . "\n";
              }
              usleep($delay);
            }
          }
        ?>
      </p>
      <div class="map" id="map_canvas"></div>
     </form>
	</body>
</html>